<?php

namespace App\Services\Accompany;

use App\Exceptions\BasicException;
use App\Models\MainDB\Accompany\AccompanyCoupon;
use App\Models\MainDB\Accompany\AccompanyCouponUser;
use App\Services\Tools\RedisService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;

class AccompanyCouponService
{

    /**
     * 优惠券列表
     * @param $userId
     * @return Builder[]|Collection
     */
    public function getList($userId)
    {
        return AccompanyCoupon::query()->select(['id', 'title'])->orderBy('id', 'desc')->get();
    }

    /**
     * 新人大转盘优惠券ID
     */
    const NEW_COUPON_ID = 1;

    /**
     * @throws BasicException
     */
    public function randomDraw($userId): array
    {

        $redis = new RedisService();
        if (!$redis->checkAccompany($userId)) {
            return ['status' => 1, 'reduce' => null];
        }
        $coupon = AccompanyCoupon::query()->where('id', self::NEW_COUPON_ID)->first();
        if (empty($coupon)) {
            throw new BasicException(10001, '优惠券不存在');
        }
        $couponUser = AccompanyCouponUser::query()->where([
            'user_id'   => $userId,
            'coupon_id' => self::NEW_COUPON_ID,
        ])->where('status','>','-1')->first();
        if ($couponUser) {
            return ['status' => 1, 'reduce' => $couponUser->reduce];
        }
        AccompanyCouponUser::query()->create([
            'user_id'    => $userId,
            'coupon_id'  => self::NEW_COUPON_ID,
            'order_id'   => 0,
            'origin'     => 1,
            'status'     => 0,
            'type'       => $coupon->type ?? 1,
            'threshold'  => $coupon->threshold,
            'reduce'     => $coupon->reduce,
            'expire_day' => $coupon->expire_day,
            'start_time' => $coupon->start_time ?? time(),
            'end_time'   => $coupon->end_time ?? time(),
            'title'      => $coupon->title ?? "",
            'refund'     => 0,
        ]);
        return ['status' => 0, 'reduce' => $coupon->reduce];
    }

    /**
     * 处理优惠卷
     * @param $price
     * @param $userId
     * @param $id
     *
     * @return array
     * @throws BasicException
     */
    public function couponPrice($price, $userId, $id = 0): array
    {
        $time  = date('Y-m-d H:i:s',time());
        $model = AccompanyCouponUser::query();
        if ($id != 0) {
            $model->where('id', $id);
        }
        $data         = $model->where('user_id', $userId)
            ->where('status', 0)
            ->where('start_time', '<', $time)
            ->where('end_time', '>', $time)
            ->first();
        if ($id > 0 && empty($data)) {
            throw new BasicException(0,'此优惠卷已使用');
        }
        $reducedPrice = 0;

        if (!empty($data)) {
            if ($data['threshold'] == 0) {
                $reducedPrice = $this->handlePrice($price, $data['type'], $data['reduce']);
            } elseif ($data['threshold'] > 0 && $data['threshold'] < $price) {
                $reducedPrice = $this->handlePrice($price, $data['type'], $data['reduce']);
            }
        }

        return [
            'reduced_price'=>$reducedPrice,
            'id' => $data['id'] ??0,

        ];


    }

    public function handlePrice($price, $type, $reduce)
    {
        if ($type == 1) { //满减
            $reducedPrice = $reduce;
        } else { //折扣
            $reducedPrice = $price * $reduce;
        }

        if ($price - $reducedPrice <= 0) { //最大优惠金额
            $reducedPrice = $price;
        }
        return $reducedPrice;

    }


}
